<?php
namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

/**
 * 活动接口
 */
class Activity extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 活动列表
     */
    public function active()
    {
        $list = Db::name('activity')->order('createtime', 'DESC')->select();
        if ( empty($list) ) {
            return $this->error('暂无活动信息',$list);
        }

        return $this->success('获取活动信息成功',$list);
    }

    /**
     * 活动是否结束或者活动是否开始
     */
    public function isOver($activityId)
    {
        $time = time();
        $endTime = Db::name('activity')->where('activity_id',$activityId)->value('endtime');
        if ( $endTime < $time ) {
            return 0;
        }
        return 1;
    }

    /**
     * 是否添加用户数据
     */
    public function getUserReceive() {
        $param = $this->request->post();
        $activityId = $param['activity_id'];
        $userId = $param['user_id'];
        $mobile = $param['mobile'];
        $email = $param['email'];
        $deviceType = $param['device_type'];
        //活动是否结束或者开始
        $res = $this->isOver($activityId);
        if ( empty($res) ) {
            return $this->error('很遗憾您来晚了,活动已结束!',$res);
        }
        //是否可以参加活动
        $result = $this->isActivity($param);
        //添加相关数据
        $rankList = $this->rank($activityId);
        $myReceive = $this->myReceiveInfo($activityId,$userId);
        $num = $this->getMyCam($activityId,$userId);
        if ( $result == 1 ) {
            $groupData = array(
                'status' => '1',
                'cam' => $num,
                'rankList' => $rankList,
                'myReceive' => $myReceive
            );
            return $this->success('您已参加过活动',$groupData);
        }else {
            $invitationCode = $this->makeInviteCode();
            if ( empty($myReceive) ) {
                $myReceive['invitation_code'] = $invitationCode;
                $myReceive['recommend_num'] = 0;
                $myReceive['invite_quantity'] = 0;
            }
            if ( empty($rankList) ) {
                $rankList['length'] = 0;
            }
            $data = array(
                'activity_id' => $activityId,
                'user_id' => $userId,
                'mobile'  => !empty($mobile) ? $mobile : '',
                'email' => !empty($email) ? $email : '',
                'invitation_code' => $invitationCode,
                'device_type' => $deviceType
            );
            $result = Db::name('receive')->data($data)->insert();
            if ( $result === false ) {
                return $this->error('获取用户参加活动信息失败',3);
            }else {
                $groupData = array(
                    'status' => '0',
                    'rankList' => $rankList,
                    'myReceive' => $myReceive
                );
                return $this->success('获取用户参加活动信息成功',$groupData);
            }
        }
    }

    /**
     * 抽奖
     */
    public function getLottery()
    {
        //判断是否还有机会抽奖
        $total = 1000000;
        $activityId = $this->request->post('activity_id');
        $userId = $this->request->post('user_id');
        $invitationCode = $this->request->post('invitation_code');
        $address = $this->request->post('address');
        $quantity = Db::name('receive')->where('activity_id',$activityId)->sum('quantity');
        $inviteQuantity = Db::name('receive')->where('activity_id',$activityId)->sum('invite_quantity');
        $sum = $quantity + $inviteQuantity;
        $remain = $total - $sum;
        if ( $remain <= 5 ) {
            return $this->success('很遗憾CAM已被领光,下次早点过来哦！');
        }
        $param = array(
            'wallet_type_name' => 'cam',
            'address' => $address
        );
        $where = array(
            'activity_id' =>$activityId,
            'address' => $address
        );
        //判断地址是否是CAM
        $url = 'http://192.168.10.120:5020/user/public/checkedAddress';
        $curlData = sendCurl($url,$param,'POST');
        $result = json_decode($curlData,true);
        if ( $result['data']['result'] != 1 ) {
            return $this->error('您输入的钱包地址不是CAM地址,请检查后重新输入',[]);
        }
        //判断地址是否领取过CAM
        $info = Db::name('receive')->where($where)->find();
        if ( !empty($info) ) {
            return $this->error('您已参与过活动',$info);
        }
        //获取CAM数量
        $num = $this->getCamRandom();
        //判断该用户输入的邀请码是系统默认的还是别人分享的邀请码
        $invitationInfo = Db::name('receive')->where('activity_id',$activityId)->where('invitation_code',$invitationCode)->find();
        $invitationId = $invitationInfo['user_id'];
        // 启动事务
        Db::startTrans();
        try {
            //更新自己的信息
            Db::name('receive')->where('activity_id',$activityId)->where('user_id',$userId)
                ->update([
                    'address' => $address,
                    'recommended_id' => $invitationId,
                    'quantity' => $num,
                    'receivetime' => time(),
                    'updatetime' => time()
                ]);
            //更新邀请用户信息
            if ( empty($invitationId) ) {
                Db::name('receive')->where('activity_id',$activityId)->where('user_id',$invitationId)->update([
                    'recommend_num' => Db::raw('recommend_num+1'),
                    'updatetime' => time()
                ]);
            }else {
                Db::name('receive')->where('activity_id',$activityId)->where('user_id',$invitationId)->update([
                    'recommend_num' => Db::raw('recommend_num+1'),
                    'invite_quantity'	=> Db::raw('invite_quantity+2'),
                    'updatetime' => time()
                ]);
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }

        return $this->success('领取CAM成功',$num);
    }

    /**
     * 判断是否参加过活动
     */
    public function isActivity($param) {
        $activityId = $param['activity_id'];
        $userId = $param['user_id'];
        $mobile = empty($param['mobile']) ? '' : $param['mobile'];
        $email = empty($param['email']) ?  '' : $param['email'];
        $deviceType = $param['device_type'];
        $where = array('activity_id'=>$activityId,'user_id'=>$userId);
        if ( !empty($deviceType) ) {
            $deviceList = Db::name('receive')->where('device_type',$deviceType)->where($where)->find();
            if ( !empty($deviceList) ) {
                return 1;
            }
        }
        if ( !empty($mobile) ) {
            $mobileList = Db::name('receive')->where('mobile',$mobile)->where($where)->find();
            if ( !empty($mobileList) ) {
                return 1;
            }
        }
        if ( !empty($email) ) {
            $emailList = Db::name('receive')->where('email',$email)->where($where)->find();
            if ( !empty($emailList) ) {
                return 1;
            }
        }

        return 0;
    }

    /**
     * 该用户获取的CAM数量
     */
    public function getMyCam($activeId,$userId)
    {
        $where = array(
            'activity_id' => $activeId,
            'user_id' => $userId
        );
        $cam = Db::name('receive')->where($where)->value('quantity');

        return $cam;
    }

    /**
     * 邀请好友排名前三的数据
     */
    public function rank($activityId)
    {
        $topThreeList = Db::name('receive')->where('activity_id',$activityId)
            ->where('user_id','<>',0)
            ->order('recommend_num','DESC')
            ->field('mobile,recommend_num')
            ->limit(3)
            ->select();

        return $topThreeList;
    }

    /**
     * 我的领取信息
     */
    public function myReceiveInfo($activityId,$userId)
    {
        $where = array('activity_id'=>$activityId,'user_id'=>$userId);
        $myInfo = Db::name('receive')->where($where)->field('invitation_code,recommend_num,invite_quantity')->find();

        return $myInfo;
    }

    /**
     * 根据概率获取用户所得的cam个数
     * @return mixed
     */
    public function getCamRandom()
    {
        $array = array(1=>99,2=>0.4,3=>0.3,4=>0.2,5=>0.1);
        $number = getRandomElement($array);
        if ( $number ==  false ) {
            $number = 0;
        }

        return $number;
    }

    /**
     * 随机获取邀请码
     */
    public  function makeInviteCode(){
        $charId = strtolower(md5(uniqid(rand(), true)));
        $code = substr($charId, 0, 6);
        //查询数据库是否存在邀请码
        $oneInfo = Db::name('receive')->where('invitation_code',$code)->select();
        if( empty($oneInfo) ) {
            return $code;
        }

        $this->makeInviteCode();
    }

    /**
     * 短链接生成
     */
    public function getShoreUrl()
    {
        $url = 'home/wallet/wallet/l/zh.html';
        $code = sprintf("%u",crc32($url));
        $showUrl = '';
        while( $code > 0 ) {
            $s = $code % 62;
            if ( $s > 35 ){
                $s = chr($s + 61);
            }elseif( $s > 9 && $s<= 35 ){
                $s = chr($s + 55);
            }
            $showUrl .= $s;
            $code = floor($code / 62);
        }
        $shortUrl = 'http://camatrix.org/' . $showUrl;

        return $this->success('成功生成短连接',$shortUrl);
    }
}

//问题活动结束提示